<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;
use App\Services\PasswordPolicyService;

class StoreUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $passwordPolicy = app(PasswordPolicyService::class);
        
        return [
            'username' => [
                'required',
                'string',
                'max:255',
                'unique:users',
                'regex:/^[a-zA-Z0-9_]+$/',
                'not_regex:/admin/i', // 禁止用户名包含'admin'（不区分大小写）
            ],
            'nickname' => 'nullable|string|max:255',
            'email' => 'nullable|email|max:255|unique:users',
            'phone' => 'nullable|string|max:20|regex:/^1[3-9]\d{9}$/|unique:users',
            'password' => ['required', 'string', $passwordPolicy->getPasswordRules()],
            'status' => 'required|integer|in:' . implode(',', [
                \App\Models\User::STATUS_DISABLED,
                \App\Models\User::STATUS_ENABLED,
            ]),
            'max_devices' => 'nullable|integer|min:1|max:20',
            'dept_id' => 'nullable|exists:departments,id',
            'role_ids' => 'nullable|array',
            'role_ids.*' => 'exists:roles,id',
            'remark' => 'nullable|string|max:500',
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages(): array
    {
        return [
            'username.required' => '用户名不能为空',
            'username.unique' => '用户名已存在',
            'username.regex' => '用户名只能包含字母、数字和下划线',
            'username.not_regex' => '用户名不能包含"admin"字符，admin为系统内置用户',
            'username.max' => '用户名长度不能超过255个字符',
            'email.email' => '邮箱格式不正确',
            'email.unique' => '邮箱已存在',
            'email.max' => '邮箱长度不能超过255个字符',
            'phone.unique' => '手机号已存在',
            'phone.regex' => '手机号格式不正确',
            'phone.max' => '手机号长度不能超过20个字符',
            'password.required' => '密码不能为空',
            'password.min' => '密码长度不能少于8位',
            'status.required' => '状态不能为空',
            'status.in' => '状态值不正确',
            'max_devices.integer' => '最大设备数必须是整数',
            'max_devices.min' => '最大设备数不能少于1',
            'max_devices.max' => '最大设备数不能超过20',
            'dept_id.exists' => '部门不存在',
            'role_ids.*.exists' => '角色不存在',
            'remark.max' => '备注长度不能超过500个字符',
        ];
    }
}

